/*
 * @Description:
 * @Author: Devin
 * @Date: 2021-11-06 15:36:44
 * @LastEditTime: 2021-11-06 16:19:39
 * @LastEditors: Devin
 * @Reference:
 */
import { useStore } from 'vuex';
import { computed } from 'vue';

export function useStateMapper(mapper: string | string[], mapFn: (arg0: any) => any) {
  const store = useStore();

  const storeStateFns = mapFn(mapper);

  const storeState: any = {};
  Object.keys(storeStateFns).forEach((fnKey) => {
    // vuex源码中mapState和mapGetters的方法中使用的是this.$store,所以更改this绑定
    const fn = storeStateFns[fnKey].bind({ $store: store });
    storeState[fnKey] = computed(fn);
  });

  return storeState;
}

export function useActionMapper(mapper: any, mapFn: (arg0: any) => any) {
  const store = useStore();

  const storeActionsFns = mapFn(mapper);

  const storeAction: any = {};

  Object.keys(storeActionsFns).forEach((fnKey) => {
    storeAction[fnKey] = storeActionsFns[fnKey].bind({ $store: store });
  });

  return storeAction;
}
